<script setup lang="tsx">
import { computed, h, ref, watch } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { Type } from 'naive-ui/es/button/src/interface';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import type { DictSearchParams, DictType } from '@/service/api';
import { deleteDict, fetchGetDictList, getFetchDictUrl } from '@/service/api';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useAuth } from '@/hooks/business/auth';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import DictOperateModal from './dict-data-operate-modal.vue';

defineOptions({
  name: 'DictDataModal'
});

interface Props {
  rowData?: DictType | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const appStore = useAppStore();
const { hasAuth } = useAuth();

const title = computed(() => {
  return `【${props.rowData?.name}】${$t('page.manage.dict.type.data')}`;
});

const model = ref<DictSearchParams>({
  label: '',
  status: undefined
});

const { columns, columnChecks, data, getData, getDataByPage, loading, pagination, searchParams } = useTable({
  apiFn: fetchGetDictList,
  immediate: false,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    dictType: null,
    status: null,
    label: null
  },
  columns: () => [
    {
      type: 'selection'
    },
    {
      key: 'id',
      title: $t('page.manage.dict.id'),
      align: 'center',
      width: 120
    },
    {
      key: 'label',
      title: $t('page.manage.dict.label'),
      align: 'center',
      width: 200
    },
    {
      key: 'value',
      title: $t('page.manage.dict.value'),
      align: 'center',
      width: 150
    },
    {
      key: 'sort',
      title: $t('page.manage.dict.sort'),
      align: 'center',
      width: 100
    },
    {
      key: 'status',
      title: $t('page.manage.dict.status'),
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'colorType',
      title: $t('page.manage.dict.colorType'),
      align: 'center',
      width: 120,
      render: row => {
        if (!row.colorType) {
          return '~';
        }
        return h(
          NButton,
          {
            type: row.colorType as Type,
            size: 'small',
            strong: true,
            secondary: true,
            style: {
              width: '80px'
            }
          },
          {
            default: () => row.colorType
          }
        );
      }
    },
    {
      key: 'cssClass',
      title: $t('page.manage.dict.cssClass'),
      align: 'center',
      width: 150
    },
    {
      key: 'remark',
      title: $t('page.manage.dict.remark'),
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 150,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:dict:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:dict:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const {
  checkedRowKeys,
  handleEdit,
  handleAdd,
  onDeleted,
  onBatchDeleted,
  fetchDataUrl,
  modelVisible,
  operateType,
  editingData
} = useTableOperate(data, getData);

const dictType = ref('');

async function init() {
  searchParams.dictType = props.rowData?.type;
  getDataByPage();
}

watch(visible, val => {
  if (val) {
    init();
  }
});

function reset() {
  model.value = {
    label: '',
    status: undefined
  };
}

function search() {
  searchParams.dictType = props.rowData?.type;
  searchParams.label = model.value.label;
  getDataByPage();
}

function handleDictAdd() {
  if (props.rowData?.type !== undefined) {
    dictType.value = props.rowData?.type;
  } else {
    dictType.value = ''; // 默认值为空字符串
  }

  handleAdd();
}

async function handleDelete(id: number) {
  // request
  const { error } = await deleteDict(id.toString());
  await onDeleted(error);
}

async function handleBatchDelete() {
  // request
  const { error } = await deleteDict(checkedRowKeys.value.join(','));

  await onBatchDeleted(error);
}

function edit(id: number) {
  fetchDataUrl.value = getFetchDictUrl(id);
  handleEdit(id);
}

function handleRefresh() {
  searchParams.dictType = props.rowData?.type;
  getDataByPage();
}
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-450">
    <NCard size="small" class="sm:flex-1-hidden card-wrapper">
      <NForm label-placement="left" label-width="auto" :show-feedback="false">
        <NGrid responsive="screen" item-responsive class="pb-5 pt-5">
          <NFormItemGi span="24 s:12 m:8" :label="$t('page.manage.dict.label')" path="label" class="pr-24px">
            <NInput v-model:value="model.label" :placeholder="$t('page.manage.dict.form.label')" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:8">
            <NSpace class="w-full" justify="end">
              <NButton @click="reset">
                <template #icon>
                  <icon-ic-round-refresh class="text-icon" />
                </template>
                {{ $t('common.reset') }}
              </NButton>
              <NButton type="primary" ghost @click="search">
                <template #icon>
                  <icon-ic-round-search class="text-icon" />
                </template>
                {{ $t('common.search') }}
              </NButton>
            </NSpace>
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NCard>
    <NCard size="small" class="mt-10 sm:flex-1-hidden card-wrapper">
      <template #header>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:dict:create"
          delete-auth="system:dict:delete"
          @add="handleDictAdd"
          @delete="handleBatchDelete"
          @refresh="handleRefresh"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="pagination"
        class="sm:h-100"
      ></NDataTable>

      <DictOperateModal
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :dict-type="dictType"
        @submitted="getDataByPage"
      />
    </NCard>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
NButton, NPopconfirm, NButton, NPopconfirm,
